package passenger

import (
	"fmt"
	"reflect"

	v1 "gitee.com/sweetsunnyflower/carpooling-server-go/app/http/controllers/api/v1"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/models/driver"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/models/passenger"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/models/user_follow"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/requests"
	"github.com/gofiber/fiber/v2"
	"github.com/spf13/cast"
)

type UserFollowsController struct {
	v1.BaseController
}

// 我关注的司机
func (controller *UserFollowsController) Index(c *fiber.Ctx) error {

	userId := controller.Auth(c)

	userFollows := user_follow.GetFollows(userId, user_follow.FOLLOW_DRIVER)

	userFollowsCount := user_follow.GetFollowsCount(userId, user_follow.FOLLOW_DRIVER)

	return controller.Json(c, fiber.Map{
		"count": userFollowsCount,
		"data":  userFollows,
	})
}

// 关注司机
func (controller *UserFollowsController) Store(c *fiber.Ctx) error {

	userId := controller.Auth(c)

	request := new(requests.UserFollowRequest)

	if errors := requests.ValidateUserFollow(c, request); len(errors) > 0 {
		return controller.ValidationError(c, errors)
	}
	if userId == request.FollowId {
		return controller.Faield(c, "自己无法关注自己")
	}
	// 查询司机师傅存在
	driver := driver.GetByUserId(request.FollowId)
	if driver.ID <= 0 {
		return controller.Faield(c, "司机不存在")
	}

	if user_follow.IsFollow(userId, request.FollowId, user_follow.FOLLOW_DRIVER) {
		return controller.Success(c)
	}

	userFollowModel := user_follow.UserFollow{
		UserId:   userId,
		FollowId: request.FollowId,
		Type:     user_follow.FOLLOW_DRIVER,
	}

	userFollowModel.Create()

	if userFollowModel.ID > 0 {
		passenger, ok := c.Locals("passenger").(passenger.Passenger)

		if !ok {
			fmt.Println(reflect.TypeOf(c.Locals("passenter")))

			return controller.Faield(c, "类型断言失败")
		}

		passenger.FollowsCount = passenger.FollowsCount + 1

		passenger.Save()

		return controller.Success(c)
	} else {
		return controller.Faield(c, "创建失败")
	}
}

// 取消关注
func (controller *UserFollowsController) Delete(c *fiber.Ctx) error {

	userId := controller.Auth(c)

	userFollowModel := user_follow.GetByFollowIdAndUserId(cast.ToUint64(c.Params("follow_id")), userId)

	if userFollowModel.ID == 0 {
		return controller.NotFound(c)
	}

	if user_follow.DeleteForever(userFollowModel) {
		passenger, ok := c.Locals("passenger").(passenger.Passenger)
		if !ok {
			fmt.Println(reflect.TypeOf(c.Locals("passenter")))
			return controller.Faield(c, "类型断言失败")
		}
		passenger.FollowsCount = passenger.FollowsCount - 1
		passenger.Save()

		return controller.Success(c)
	}

	return controller.Faield(c, "删除失败")
}
